package com.moneywelcome.aliyun;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 *阿里云文件系统，需配置
 *       地区节点域名      oss-properties.endpoint =
 *       账号keyid        oss-properties.accessKeyId =
 *       账号KeySecret    oss-properties.accessKeySecret =
 */
@Component
//@ConfigurationProperties(prefix = "oss-properties")
@Data
public class AliyunOssUtil {
    /**
     地区节点域名
     */
    @Value("${oss-properties.endpoint}")
    private String endpoint;

    /**
     账号keyid
     */
    @Value("${oss-properties.accessKeyId}")
    private String accessKeyId;

    /**
     账号KeySecret
     */
    @Value("${oss-properties.accessKeySecret}")
    private String accessKeySecret;

    //上传
    public String upload(String fileName, String bucketName, InputStream fileInputStream) {
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build("https://"+endpoint,
                    accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, fileName, fileInputStream);
            String url = "http://"+bucketName+"." + endpoint + "/" + fileName;
            return url;
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
    }

    // 文件删除
    public boolean delete(String fileName,String bucketName) {
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build("https://"+endpoint,
                    accessKeyId, accessKeySecret);
            ossClient.deleteObject(bucketName, fileName);
            return true;
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
    }
}
